#include <jni.h>
#include "include/FFmpegPlay.h"

#include "include/Constant.h"
#include "include/JniCallJava.h"

extern "C" {
#include "libavformat/avformat.h"
#include "libswresample/swresample.h"
}

FFmpegPlay *pFFmpegPlay = nullptr;
JniCallJava *pJniCallJava = nullptr;

JavaVM *pJavaVM = nullptr;

extern "C"
JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
    pJavaVM = vm;
    JNIEnv *env;
    if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR;
    }
    return JNI_VERSION_1_6;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_frank_player_media_AudioPlayer_nPlay(JNIEnv *env, jobject thiz) {
    if (pFFmpegPlay != nullptr) {
        pFFmpegPlay->play();
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_frank_player_media_AudioPlayer_nPrepare(JNIEnv *env, jobject thiz, jstring url) {
    const char *mediaUrl = env->GetStringUTFChars(url, nullptr);
    if (pFFmpegPlay == nullptr) {
        pJniCallJava = new JniCallJava(pJavaVM, env, thiz);
        pFFmpegPlay = new FFmpegPlay(pJniCallJava, mediaUrl);
        pFFmpegPlay->prepare();
    }
    env->ReleaseStringUTFChars(url, mediaUrl);
}

extern "C"
JNIEXPORT void JNICALL
Java_com_frank_player_media_AudioPlayer_nPrepareAsync(JNIEnv *env, jobject thiz, jstring url) {
    const char *mediaUrl = env->GetStringUTFChars(url, nullptr);
    if (pFFmpegPlay == nullptr) {
        pJniCallJava = new JniCallJava(pJavaVM, env, thiz);
        pFFmpegPlay = new FFmpegPlay(pJniCallJava, mediaUrl);
        pFFmpegPlay->prepareAsync();
    }
    env->ReleaseStringUTFChars(url, mediaUrl);
}